package structure.adapte.springmvc;

import java.util.ArrayList;
import java.util.List;

/**
 * @author dali
 * @date 2021-07-12 21:22
 * @Description
 */

public class DispatcherServletTest {

    public static List<HandlerAdapter> handlerList = new ArrayList<>();

    //做简化，实际spring使用反射将adapter假如list中，如果扩展，只需要在配置文件中添加
    public DispatcherServletTest() {
        handlerList.add(new HttpHandlerAdapter());
        handlerList.add(new SimpleHandlerAdapter());
    }

    /**
     * 传参做简化，实际spring源码中根据request来获取handler
     * @param handler
     */
    protected void doDispatch(Handler handler) {
        //根据不同的handler进行适配转换
        HandlerAdapter adapter = this.getHandler(handler);
        //进行方法调用
        if (adapter != null) {
            adapter.handler(handler);
        }
    }

    protected HandlerAdapter getHandler(Handler handler) {
        for (HandlerAdapter adapter : handlerList) {
            if (adapter.supports(handler)) {
                return adapter;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        new DispatcherServletTest().doDispatch(new SimpleHandel());
    }
}
